//
//  QRCodeScanVC.m
//  EPTool
//
//  Created by guoshiqing on 2018/4/27.
//  Copyright © 2018年 云数动能科技. All rights reserved.
//

#import "QRCodeScanVC.h"
#import "QRCodeDisplayView.h"
#import <AVFoundation/AVFoundation.h>
#import "UIView+DDAddition.h"
#import "QRCodeUtil.h"
#import "UserSettings.h"
#import "Message.h"

#define Y_OffSet 100  // 扫描不到，或者在选定区域外被扫描到，都可能是选定区域和扫描区不一致导致的，修改这个值即可

@interface QRCodeScanVC () <AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate>
{
    UIButton * _scanLightBtn;
    UIImageView  * _qrcodeScanline;
    UIStatusBarStyle _statusBarStyle;
}

@property (nonatomic, strong) UIView *scanRectView;
@property (nonatomic, assign) BOOL isShowMyQRCode;  //判断是否显示我的二维码，是的话暂停扫描二维码

@property (strong, nonatomic) AVCaptureDevice            *device;
@property (strong, nonatomic) AVCaptureDeviceInput       *input;
@property (strong, nonatomic) AVCaptureMetadataOutput    *output;
@property (strong, nonatomic) AVCaptureSession           *captureSession;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer *capturePreview;
@property (strong, nonatomic) UILabel  *contentLbl;
@property (strong, nonatomic) UIButton *myQRCodeBtn;

@end

@implementation QRCodeScanVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configView];
    
    self.title = NSLocalizedString(@"ScanQRCode", @"扫描二维码");

    [self createNavBarRightButtonWithImageName:@"scan_light"];
    WEAKSELF
    self.rightNavButtonBlock = ^{
        [weakSelf onRightItemClick];
    };
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _statusBarStyle = [UIApplication sharedApplication].statusBarStyle;
    [self setStatusBarAndNavigationBarWithStype:UIStatusBarStyleLightContent andTitleColor:[UIColor clearColor]];
    [self setupCamera];
}

- (void)onBackClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)configView{
    
    CGSize windowSize = [UIScreen mainScreen].bounds.size;
    
    //    CGSize scanSize = CGSizeMake(windowSize.width*3/4, windowSize.width*3/4);
    CGSize scanSize = CGSizeMake(258, 258);
//    CGRect scanRect = CGRectMake((windowSize.width-scanSize.width)/2, (windowSize.height-scanSize.height)/2-20, scanSize.width, scanSize.height);
//
//    scanRect = CGRectMake(scanRect.origin.y/windowSize.height, scanRect.origin.x/windowSize.width, scanRect.size.height/windowSize.height,scanRect.size.width/windowSize.width);
    
    self.scanRectView = [UIView new];
    [self.view addSubview:self.scanRectView];
    self.scanRectView.frame = CGRectMake(0, 0, scanSize.width, scanSize.height);
    self.scanRectView.center= CGPointMake(CGRectGetMidX([UIScreen mainScreen].bounds), CGRectGetMidY([UIScreen mainScreen].bounds)-Y_OffSet);
    
    //冲击波
    _qrcodeScanline = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"qrcode_scanline_qrcode"]];
    _qrcodeScanline.frame = CGRectMake(0, 0, self.scanRectView.width, 5);
    [self.scanRectView addSubview:_qrcodeScanline];
    
    UIImageView * ScanBgView = [[UIImageView alloc] initWithFrame:self.scanRectView.bounds];
    ScanBgView.contentMode   = UIViewContentModeScaleAspectFit;
    UIImage     * image      = [UIImage imageNamed:@"qrcode_border"];
    
    // 设置端盖的值
    CGFloat top    = 25;
    CGFloat left   = 25;
    CGFloat bottom = 26;
    CGFloat right  = 26;
    
    // 设置端盖的值
    UIEdgeInsets edgeInsets = UIEdgeInsetsMake(top, left, bottom, right);
    // 设置拉伸的模式
    UIImageResizingMode mode = UIImageResizingModeTile;
    
    // 拉伸图片
    UIImage *newImage = [image resizableImageWithCapInsets:edgeInsets resizingMode:mode];
    [ScanBgView setImage:newImage];
    
    [self.scanRectView addSubview:ScanBgView];
    
    self.contentLbl = [UILabel new];
    [self.view addSubview:self.contentLbl];
    self.contentLbl.frame = CGRectMake(0, self.scanRectView.bottom + 10, UI_SCREEN_WIDTH, 40);
    self.contentLbl.textAlignment = NSTextAlignmentCenter;
    self.contentLbl.text = NSLocalizedString(@"ScanQRCodePoint", @"将取景框对准二维码，即可自动扫描");
    self.contentLbl.textColor = [UIColor whiteColor];
    self.myQRCodeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.myQRCodeBtn.frame = CGRectMake(0, self.contentLbl.bottom , UI_SCREEN_WIDTH, 60);
    self.myQRCodeBtn.centerX = self.scanRectView.centerX;
    [self.myQRCodeBtn setTitle:@"我的二维码" forState:UIControlStateNormal];
    [self.myQRCodeBtn addTarget:self action:@selector(showQRCodeDisplayAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //绘制遮罩图
    UIView * bgViewTop = [UIView new];
    bgViewTop.backgroundColor = [UIColor blackColor];
    bgViewTop.alpha   = 0.5;
    bgViewTop.top     = 0;
    bgViewTop.left    = 0;
    bgViewTop.width   = self.view.width;
    bgViewTop.height  = self.scanRectView.top;
    [self.view addSubview:bgViewTop];
    
    UIView * bgViewLeft = [UIView new];
    bgViewLeft.backgroundColor = [UIColor blackColor];
    bgViewLeft.alpha   = 0.5;
    bgViewLeft.top     = self.scanRectView.top;
    bgViewLeft.left    = 0;
    bgViewLeft.width   = self.scanRectView.left;
    bgViewLeft.height  = self.scanRectView.height;
    [self.view addSubview:bgViewLeft];
    
    UIView * bgViewRight = [UIView new];
    bgViewRight.backgroundColor = [UIColor blackColor];
    bgViewRight.alpha   = 0.5;
    bgViewRight.top     = self.scanRectView.top;
    bgViewRight.left    = self.scanRectView.right;
    bgViewRight.width   = self.scanRectView.left;
    bgViewRight.height  = self.scanRectView.height;
    [self.view addSubview:bgViewRight];
    
    UIView * bgViewBottom = [UIView new];
    bgViewBottom.backgroundColor = [UIColor blackColor];
    bgViewBottom.alpha   = 0.5;
    bgViewBottom.top     = self.scanRectView.bottom;
    bgViewBottom.left    = 0;
    bgViewBottom.width   = self.view.width;
    bgViewBottom.height  = self.view.height - self.scanRectView.bottom;
    [self.view addSubview:bgViewBottom];
    
    // 本项目不需要 我的二维码
//    [self.view addSubview:self.myQRCodeBtn];
}

-(void)setupCamera
{
    WEAKSELF
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //开始捕获
                [weakSelf.captureSession startRunning];
            });
        } else {  //未授权：
            //返回主线程处理：
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf showAlertWithTitle:MSG_NO_PERMIT_CAMERA];
            });
        }
    }];
}

- (AVCaptureSession *)captureSession
{
    if (!_captureSession) {
        CGSize windowSize = [UIScreen mainScreen].bounds.size;
        
        CGSize scanSize = CGSizeMake(258, 258);
        
        // 设置画面感兴趣的区域 https://blog.csdn.net/lixianyue1991/article/details/70894982
        CGRect scanRect = CGRectMake((windowSize.width-scanSize.width)/2, (windowSize.height-scanSize.height)/2-Y_OffSet, scanSize.width, scanSize.height);
        
        scanRect = CGRectMake(scanRect.origin.y/windowSize.height, scanRect.origin.x/windowSize.width, scanRect.size.height/windowSize.height,scanRect.size.width/windowSize.width);
        
        self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
        
        self.output = [[AVCaptureMetadataOutput alloc]init];
        [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        
        _captureSession = [[AVCaptureSession alloc]init];
        [_captureSession setSessionPreset:([UIScreen mainScreen].bounds.size.height<500)?AVCaptureSessionPreset640x480:AVCaptureSessionPresetHigh];
        [_captureSession addInput:self.input];
        [_captureSession addOutput:self.output];
        self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
        self.output.rectOfInterest = scanRect;
        
        [self.capturePreview removeFromSuperlayer];
        
        self.capturePreview = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
        self.capturePreview.videoGravity = AVLayerVideoGravityResizeAspectFill;
        self.capturePreview.frame = [UIScreen mainScreen].bounds;
        [self.view.layer insertSublayer:self.capturePreview atIndex:0];
    }
    return _captureSession;
}

-(void)onRightItemClick
{
    [_device lockForConfiguration:nil];
    //判断闪光灯是否亮着
    if(_device.torchMode == AVCaptureTorchModeOff)
    {
        [_scanLightBtn setImage:[UIImage imageNamed:@"scan_ligh_close"] forState:UIControlStateNormal];
        //打开闪光灯
        [_device setTorchMode:AVCaptureTorchModeOn];
        [_device setFlashMode:AVCaptureFlashModeOn];
    }
    else
    {
        [_scanLightBtn setImage:[UIImage imageNamed:@"scan_light"] forState:UIControlStateNormal];
        //关闭闪光灯
        [_device setTorchMode:AVCaptureTorchModeOff];
        [_device setFlashMode:AVCaptureFlashModeOff];
    }
    [_device unlockForConfiguration];
}

#pragma mark - 跳转到我的二维码
- (void)showQRCodeDisplayAction:(UIButton *)sender
{
    _isShowMyQRCode = YES;
    
//    WEAKSELF
//    [QRCodeDisplayView createQRCodeViewWithQRImage:[QRCodeUtil
//                                                    createQRCodeWithString:[NSString stringWithFormat:@"%@%@%@", SDKSettings.ecServerUrl,MY_QRCODE_URL,[RNUSDK sharedSDK].userId]
//                                                    qrSize:CGSizeMake(100, 100)]
//                                         andOffset:CGPointMake(0, -45)
//                                     andCloseBlock:^(BOOL isClose)
//     {
//         weakSelf.isShowMyQRCode = !isClose; //如果是关闭则可以扫描
//     }];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self startAnimation];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [_scanLightBtn setImage:[UIImage imageNamed:@"scan_light"] forState:UIControlStateNormal];
    [_device lockForConfiguration:nil];
    //关闭闪光灯
    [_device setTorchMode:AVCaptureTorchModeOff];
    [_device setFlashMode:AVCaptureFlashModeOff];
    [_device unlockForConfiguration];
    
    [[UIApplication sharedApplication] setStatusBarStyle:_statusBarStyle];
}

// 开启冲击波动画
- (void)startAnimation
{
    // 1.设置冲击波底部和容器视图顶部对齐
    //    qrcode_scanline_qrcode
    
    // 刷新UI
    [self.view layoutIfNeeded];
    
    // 2.执行扫描动画
    [UIView animateWithDuration:1.0 animations:^{
        // 无线重复动画
        [UIView setAnimationRepeatCount:MAXFLOAT];
        self->_qrcodeScanline.top = self.scanRectView.height;
        // 刷新UI
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if ( (metadataObjects.count == 0) || _isShowMyQRCode )
    {
        return;
    }
    
    AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
    
    if (metadataObjects.count > 0) {
        
        [_scanLightBtn setImage:[UIImage imageNamed:@"scan_light"] forState:UIControlStateNormal];
        [_device lockForConfiguration:nil];
        //关闭闪光灯
        [_device setTorchMode:AVCaptureTorchModeOff];
        [_device setFlashMode:AVCaptureFlashModeOff];
        [_device unlockForConfiguration];
        
        [_captureSession stopRunning];
        
//        NSLog(@"metadataObject.stringValue = %@",metadataObject.stringValue);
//        NSString *stringValue = metadataObject.stringValue;
        NSString *stringValue = [metadataObject.stringValue stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        // 扫码进行申请加入团队的操作
        if ([stringValue containsString:@"verifytoken"] && [stringValue containsString:@"name"]) {
            NSArray *urlArr = [stringValue componentsSeparatedByString:@"?"];
            NSString *urlQuery = urlArr[1];
            if (urlQuery.length > 0) {
                NSArray *arr1 = [urlQuery componentsSeparatedByString:@"&"];
                NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
                for (int i = 0; i < arr1.count; i++) {
                    NSString *str = arr1[i];
                    NSUInteger index = [str rangeOfString:@"="].location;
                    NSString *key = [str substringToIndex:index];
                    NSString *value = [str substringFromIndex:index+1];
                    [dic setObject:value forKey:key];
                }
//                NSLog(@"dic = %@",dic);
                UserSaveInfo.joinTeamName = dic[@"name"];
                UserSaveInfo.joinTeamToken = dic[@"verifytoken"];
            }
            [self.navigationController popViewControllerAnimated:YES];
        } else if ([stringValue containsString:@"RecruitApplyCheckIn"]) {
            NSArray *urlArr = [stringValue componentsSeparatedByString:@"//"];
            NSDictionary *dic = @{@"key": @"RecruitApplyCheckIn", @"value": urlArr[1]};
            if (self.resultBlock) {
                self.resultBlock(dic);
            }
            [self.navigationController popViewControllerAnimated:YES];
        } else if ([stringValue containsString:@"TrainingApplyCheckIn"]) {
            NSArray *urlArr = [stringValue componentsSeparatedByString:@"//"];
            NSDictionary *dic = @{@"key": @"TrainingApplyCheckIn", @"value": urlArr[1]};
            if (self.resultBlock) {
                self.resultBlock(dic);
            }
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            WEAKSELF
            [ToastView showMsg:NSLocalizedString(@"ScanQRCodeIsFail", @"无效二维码") inView:self.view dismissBlock:^{
                [weakSelf dismissVC];
            }];
        }
    }
}

- (NSDictionary*)dictionaryFromQuery:(NSString*)query {
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        if (kv.count == 2) {
            NSString *val =[[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [params setObject:val forKey:[kv objectAtIndex:0]];
        }
    }
    return params;
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [_captureSession startRunning];
}

// 显示深色和浅色两种导航栏样式
- (void)setStatusBarAndNavigationBarWithStype:(UIStatusBarStyle)stype andTitleColor:(UIColor *)color
{
    // 设置状态栏
    [[UIApplication sharedApplication] setStatusBarStyle:stype];
    self.navigationController.navigationBar.translucent = NO;
}

@end
